package com.jar.exercise.集合和数据结构.HashMap计算hash取余数;

/**
 * 当需要对2的次幂进行求余时，可以是使用&运算符来代替
 * & 位与运算  两边都是1,结果才为1
 * 15 % 16 取模运算
 * ===>
 * 15 & (16 - 1)
 * 1111
 * & 1111
 * 1111
 * <p>
 * 1010
 * 111
 * <p>
 * 30 % 8
 * 11110
 * &   111
 * 11
 * 100
 * 111
 */
public class Demo {
	public static void main(String[] args) {
		// 1111
		// 1111
		int i1 = 15 % 16;
		int i2 = 16 % 9;
		System.out.println(i2);
		int i = 15 & 15;
		//  0001
		// 01111
		//  1

	}
}

/**
 * 直接【求余】和【按位】运算的差别验证
 */
class Demo2 {
	public static void main(String[] args) {
		long currentTimeMillis = System.currentTimeMillis();
		int a = 0;
		int times = 10000 * 10000;
		for (long i = 0; i < times; i++) {
			a = 9999 % 1024;
		}
		long currentTimeMillis2 = System.currentTimeMillis();

		int b = 0;
		for (long i = 0; i < times; i++) {
			b = 9999 & (1024 - 1);
		}

		long currentTimeMillis3 = System.currentTimeMillis();
		System.out.println(a + "," + b);
		System.out.println("%: " + (currentTimeMillis2 - currentTimeMillis));
		System.out.println("&: " + (currentTimeMillis3 - currentTimeMillis2));
	}
}
